<?php
namespace app\controller;

use app\BaseController;
use app\model\User as UserModel;
use app\model\Role as RoleModel;
use think\facade\Validate;
use think\facade\Db;

class User extends BaseController
{
    /**
     * 获取用户列表
     */
    public function index()
    {
        // 获取请求参数
        $params = $this->request->get();
        
        // 构建查询
        $query = UserModel::withoutField('password');
        
        // 按用户名搜索
        if (!empty($params['username'])) {
            $query = $query->whereLike('username', '%' . $params['username'] . '%');
        }
        
        // 按姓名搜索
        if (!empty($params['name'])) {
            $query = $query->whereLike('name', '%' . $params['name'] . '%');
        }
        
        // 按部门搜索
        if (!empty($params['department'])) {
            $query = $query->whereLike('department', '%' . $params['department'] . '%');
        }
        
        // 按状态搜索
        if (isset($params['status']) && $params['status'] !== '') {
            $query = $query->where('status', $params['status']);
        }
        
        // 关联角色
        $query = $query->with(['roles']);
        
        // 分页
        $list = $query->paginate([
            'list_rows' => $params['pageSize'] ?? 10,
            'page' => $params['page'] ?? 1,
        ]);
        
        return $this->success('获取成功', $list);
    }
    
    /**
     * 添加用户
     */
    public function add()
    {
        // 获取请求数据
        $data = $this->request->post();
        
        // 验证数据
        $validate = Validate::rule([
            'username' => 'require|alphaDash|unique:user',
            'password' => 'require|min:6',
            'name' => 'require',
            'email' => 'email',
            'phone' => 'mobile',
            'department' => 'max:50',
            'position' => 'max:50',
            'status' => 'require|in:0,1',
            'role_ids' => 'array'
        ]);
        
        if (!$validate->check($data)) {
            return $this->error('参数错误：' . $validate->getError());
        }
        
        // 密码加密
        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        
        // 启动事务
        Db::startTrans();
        try {
            // 创建用户
            $user = UserModel::create([
                'username' => $data['username'],
                'password' => $data['password'],
                'name' => $data['name'],
                'email' => $data['email'] ?? '',
                'phone' => $data['phone'] ?? '',
                'avatar' => $data['avatar'] ?? '',
                'department' => $data['department'] ?? '',
                'position' => $data['position'] ?? '',
                'status' => $data['status'],
            ]);
            
            // 关联角色
            if (!empty($data['role_ids'])) {
                $user->roles()->saveAll($data['role_ids']);
            }
            
            Db::commit();
            return $this->success('添加成功', $user);
            
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('添加失败：' . $e->getMessage());
        }
    }
    
    /**
     * 编辑用户
     */
    public function edit()
    {
        // 获取请求数据
        $data = $this->request->put();
        
        // 验证数据
        $validate = Validate::rule([
            'id' => 'require|number',
            'username' => 'alphaDash',
            'name' => 'require',
            'email' => 'email',
            'phone' => 'mobile',
            'department' => 'max:50',
            'position' => 'max:50',
            'status' => 'require|in:0,1',
            'role_ids' => 'array'
        ]);
        
        if (!$validate->check($data)) {
            return $this->error('参数错误：' . $validate->getError());
        }
        
        // 查询用户
        $user = UserModel::find($data['id']);
        if (!$user) {
            return $this->error('用户不存在');
        }
        
        // 如果修改了用户名，需要检查唯一性
        if (isset($data['username']) && $data['username'] !== $user->username) {
            if (UserModel::where('username', $data['username'])->where('id', '<>', $data['id'])->find()) {
                return $this->error('用户名已存在');
            }
        }
        
        // 启动事务
        Db::startTrans();
        try {
            // 更新用户信息
            $user->save([
                'username' => $data['username'] ?? $user->username,
                'name' => $data['name'],
                'email' => $data['email'] ?? '',
                'phone' => $data['phone'] ?? '',
                'avatar' => $data['avatar'] ?? $user->avatar,
                'department' => $data['department'] ?? '',
                'position' => $data['position'] ?? '',
                'status' => $data['status'],
            ]);
            
            // 更新角色关联
            if (isset($data['role_ids'])) {
                $user->roles()->detach();
                if (!empty($data['role_ids'])) {
                    // 修复角色关联方式，使用 sync 方法同步角色ID
                    $user->roles()->sync($data['role_ids']);
                }
            }
            
            Db::commit();
            return $this->success('更新成功');
            
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('更新失败：' . $e->getMessage());
        }
    }
    
    /**
     * 删除用户
     * @param int $id 用户ID
     */
    public function delete($id)
    {
        // 验证参数
        if (!$id || !is_numeric($id)) {
            return $this->error('参数错误');
        }
        
        // 查询用户
        $user = UserModel::find($id);
        if (!$user) {
            return $this->error('用户不存在');
        }
        
        // 不能删除超级管理员
        if ($user->username === 'admin') {
            return $this->error('不能删除超级管理员');
        }
        
        // 启动事务
        Db::startTrans();
        try {
            // 删除用户角色关联
            $user->roles()->detach();
            
            // 删除用户
            $user->delete();
            
            Db::commit();
            return $this->success('删除成功');
            
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('删除失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取用户详情
     * @param int $id 用户ID
     */
    public function detail($id)
    {
        // 获取当前用户ID
        $userId = $this->request->get('id');
     
        // 验证参数
        if (!$userId || !is_numeric($userId)) {
            return $this->error('参数错误');
        }
        
        // 查询用户
        $user = UserModel::withoutField('password')->with(['roles'])->find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }
        
        return $this->success('获取成功', $user);
    }
    
    /**
     * 重置密码
     */
    public function resetPassword()
    {
        // 获取请求数据
        $data = $this->request->post();
        
        // 验证数据
        $validate = Validate::rule([
            'id' => 'require|number',
            'password' => 'require|min:6',
        ]);
        
        if (!$validate->check($data)) {
            return $this->error('参数错误：' . $validate->getError());
        }
        
        // 查询用户
        $user = UserModel::find($data['id']);
        if (!$user) {
            return $this->error('用户不存在');
        }
        
        // 更新密码
        $user->password = password_hash($data['password'], PASSWORD_DEFAULT);
        if ($user->save()) {
            return $this->success('密码重置成功');
        } else {
            return $this->error('密码重置失败');
        }
    }
    
    /**
     * 修改密码
     */
    public function changePassword()
    {
        // 获取请求数据
        $data = $this->request->post();
        
        // 验证数据
        $validate = Validate::rule([
            'old_password' => 'require',
            'new_password' => 'require|min:6|different:old_password',
            'confirm_password' => 'require|confirm:new_password',
        ]);
        
        if (!$validate->check($data)) {
            return $this->error('参数错误：' . $validate->getError());
        }
        
        // 获取当前用户ID
        $userId = $this->request->userId;
        if (!$userId) {
            return $this->error('未登录');
        }
        
        // 查询用户
        $user = UserModel::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }
        
        // 验证旧密码
        if (!$user->verifyPassword($data['old_password'])) {
            return $this->error('旧密码错误');
        }
        
        // 更新密码
        $user->password = password_hash($data['new_password'], PASSWORD_DEFAULT);
        if ($user->save()) {
            return $this->success('密码修改成功');
        } else {
            return $this->error('密码修改失败');
        }
    }
    
    /**
     * 获取用户权限
     */
    public function permissions()
    {
        // 获取当前用户ID
        $userId = $this->request->userId;
        if (!$userId) {
            return $this->error('未登录');
        }
        
        // 查询用户
        $user = UserModel::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }
        
        // 获取用户权限
        $permissions = $user->getPermissions();
        
        return $this->success('获取成功', $permissions);
    }
    
    /**
     * 更新用户个人信息
     */
    public function updateProfile()
    {
        // 获取请求数据
        $data = $this->request->put();
        
        // 验证数据
        $validate = Validate::rule([
            'name' => 'max:50',
            'email' => 'email',
            'phone' => 'mobile',
            'avatar' => 'max:255',
        ]);
        
        if (!$validate->check($data)) {
            return $this->error('参数错误：' . $validate->getError());
        }
        
        // 获取当前用户ID
        $userId = $this->request->userId;
        if (!$userId) {
            return $this->error('未登录');
        }
        
        // 查询用户
        $user = UserModel::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }
        
        // 更新用户信息
        $updateData = [];
        if (isset($data['name'])) $updateData['name'] = $data['name'];
        if (isset($data['email'])) $updateData['email'] = $data['email'];
        if (isset($data['phone'])) $updateData['phone'] = $data['phone'];
        if (isset($data['avatar'])) $updateData['avatar'] = $data['avatar'];
        
        if (!empty($updateData)) {
            if ($user->save($updateData)) {
                return $this->success('更新成功');
            } else {
                return $this->error('更新失败');
            }
        } else {
            return $this->error('没有需要更新的数据');
        }
    }
    
    /**
     * 获取用户个人信息
     */
    public function profile()
    {
        // 获取当前用户ID
        $userId = $this->request->userId;

        if (!$userId) {
            return $this->error('未登录');
        }
        
        // 查询用户
        $user = UserModel::withoutField('password')->with(['roles'])->find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }
        
        return $this->success('获取成功', $user);
    }
} 